<template>
  <div style="flex-direction: column; height: 100vh" v-if="isComponentMounted" class="app-container">
    <div class="header">
      <button class="back-button" @click="handleBack">返回</button>
      <span class="title">产品生产装配碳排放值收集 / {{ materialOrProductName }}</span>
      <div class="header-buttons">
        <el-button type="primary" link :icon="Document" @click="save">保存</el-button>
      </div>
    </div>
    <!-- 输入弹出窗口 -->
    <el-dialog v-model="isInputModalOpen" title="输入能耗量" width="400px">
      <el-form :model="inputForm" :rules="inputRules" ref="inputRuleFormRef">
        <el-form-item label="消耗量" prop="consumption" :label-width="formLabelWidth">
          <el-input
            v-model="inputForm.consumption"
            placeholder="请输入消耗量"
            @input="validateNumber('consumption', inputForm)"
          />
        </el-form-item>
        <el-form-item label="单位" prop="unit" :label-width="formLabelWidth">
          <el-select v-model="inputForm.unit" placeholder="请选择单位">
            <el-option v-for="item in IOUnitType" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="isInputModalOpen = false">取消</el-button>
          <el-button type="primary" @click="updateNodeConsumption">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 输出弹出窗口 -->
    <el-dialog v-model="isOutputModalOpen" title="输出" width="400px">
      <el-form :model="outputForm" :rules="outputRules" ref="outputRuleFormRef">
        <el-form-item label="数量" prop="consumption" :label-width="formLabelWidth">
          <el-input
            v-model="outputForm.consumption"
            placeholder="请输入数量"
            @input="validateNumber('consumption', outputForm)"
          />
        </el-form-item>
        <el-form-item label="单位" prop="unit" :label-width="formLabelWidth">
          <el-select v-model="outputForm.unit" placeholder="请选择单位">
            <el-option v-for="item in IOUnitType" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="isOutputModalOpen = false">取消</el-button>
          <el-button type="primary" @click="updateNodeOutput()"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 详情弹窗（只读，风格与 selfMadeEmission.vue 一致） -->
    <el-dialog v-model="isDetailOpen" title="查看详情" width="860px" :close-on-click-modal="false">
      <!-- 只读信息 -->
      <el-descriptions :column="1" size="default" border>
        <el-descriptions-item label="工序编号">{{ detailForm.processId }}</el-descriptions-item>
        <el-descriptions-item label="工序名称">{{ detailForm.processName }}</el-descriptions-item>
        <el-descriptions-item label="工序描述">{{ detailForm.description }}</el-descriptions-item>
      </el-descriptions>

      <!-- 所属设备 -->
      <h4 style="margin: 20px 0 10px; font-weight: 600">所属设备</h4>
      <el-table
        :data="equipmentBindings"
        style="width: 100%"
        max-height="400px"
        border
        :header-cell-style="{ background: '#f5f7fa', color: '#606266', height: '50px', fontWeight: 600 }"
        :cell-style="{ height: '45px' }"
      >
        <el-table-column type="index" label="序号" align="center" min-width="60" />
        <el-table-column label="设备名称" align="center" min-width="180">
          <template #default="{ row }">{{ row.equipmentName }}</template>
        </el-table-column>
      </el-table>

      <template #footer>
        <el-button type="primary" @click="isDetailOpen = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 节点详情对话框 -->
    <el-dialog v-model="nodeDetailDialogVisible" title="节点详情" width="500px">
      <el-descriptions :column="1" border>
        <!-- 输出节点详情 -->
        <template v-if="currentNodeType === 'input'">
          <el-descriptions-item label="碳排放源">
            {{ getFactorTypeLabel(currentNodeDetail.label) || "暂未定义" }}
          </el-descriptions-item>
          <el-descriptions-item label="消耗量">
            {{ currentNodeDetail.consumption || "暂未定义" }}
          </el-descriptions-item>
          <el-descriptions-item label="单位">
            {{ getUnitLabel(currentNodeDetail.unit) || "暂未定义" }}
          </el-descriptions-item>
          <el-descriptions-item label="设备名称">
            {{ getEquipmentName(currentNodeDetail.equipmentId) || "暂未定义" }}
          </el-descriptions-item>
          <el-descriptions-item label="数据来源">
            {{ currentNodeDetail.dataSource || "暂未定义" }}
          </el-descriptions-item>
        </template>

        <!-- 输入节点详情 -->
        <template v-if="currentNodeType === 'output'">
          <el-descriptions-item label="碳排放源">
            {{ currentNodeDetail.label || "暂未定义" }}
          </el-descriptions-item>
          <el-descriptions-item label="类型">
            {{ getOutputTypeLabel(currentNodeDetail.output) || "暂未定义" }}
          </el-descriptions-item>
          <el-descriptions-item label="输出量">
            {{ currentNodeDetail.consumption || "暂未定义" }}
          </el-descriptions-item>
          <el-descriptions-item label="单位">
            {{ getUnitLabel(currentNodeDetail.unit) || "暂未定义" }}
          </el-descriptions-item>
        </template>
      </el-descriptions>
    </el-dialog>

    <div class="process-flow-container">
      <VueFlow
        v-model:nodes="nodes"
        v-model:edges="edges"
        :default-viewport="{ x: 0, y: 0, zoom: 1 }"
        fit-view-on-init
        class="confirm-flow"
        :min-zoom="0.2"
        :max-zoom="4"
        :nodes-draggable="false"
        :fit-view-options="{ padding: 0.2 }"
      >
        <Background color="#3eaea4" />
        <template #node-default="props">
          <toolBarDefault :id="props.id" :data="props.data" @toolbar-action="handleToolbarAction" />
        </template>
        <template #node-output="props">
          <toolBarInput :id="props.id" :data="props.data" @toolbar-action="handleToolbarAction" />
        </template>
        <template #node-input="props">
          <toolBarOutput :id="props.id" :data="props.data" @toolbar-action="handleToolbarAction" />
        </template>
      </VueFlow>
    </div>

    <!-- 数据来源选择对话框 -->
    <el-dialog v-model="dataSourceDialogVisible" title="选择数据来源" width="500px" append-to-body>
      <div class="data-source-options">
        <div
          v-for="source in dataSources"
          :key="source.value"
          class="data-source-option"
          @click="handleDataSourceSelect(source.value)"
        >
          <div class="source-icon">
            <el-icon :size="24">
              <component :is="source.icon" />
            </el-icon>
          </div>
          <div class="source-info">
            <h4>{{ source.label }}</h4>
            <p>{{ source.description }}</p>
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 选择分配层次对话框 -->
    <el-dialog v-model="allocationLevelDialogVisible" title="选择分配层次" width="500px" append-to-body>
      <div class="allocation-level-options">
        <div
          v-for="level in allocationLevels"
          :key="level.value"
          class="allocation-level-option"
          @click="handleAllocationLevelSelect(level.value)"
        >
          <div class="level-icon">
            <el-icon :size="24">
              <component :is="level.icon" />
            </el-icon>
          </div>
          <div class="level-info">
            <h4>{{ level.label }}</h4>
            <p>{{ level.description }}</p>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script lang="tsx" setup>
import { onMounted, onBeforeUnmount, reactive, ref, nextTick, watch, computed } from "vue";
import { VueFlow, type Node, type Edge } from "@vue-flow/core";
import { Background } from "@vue-flow/background";
// import { MiniMap } from "@vue-flow/minimap";
// import { Controls } from "@vue-flow/controls";
import toolBarDefault from "@/views/proTable/components/toolBarDNode.vue";
import toolBarInput from "@/views/proTable/components/toolBarINode.vue";
import toolBarOutput from "@/views/proTable/components/toolBarONode.vue";
import { ElMessage, FormInstance } from "element-plus";
import { Edit, Document, Connection, Share, Platform } from "@element-plus/icons-vue";
import { IOUnitType, factorType, outputType } from "@/utils/serviceDict";
import axios from "axios";
import { useRoute, useRouter } from "vue-router";
import { initializeFlowChart, initializeIONodes, saveFlowChart } from "@/utils/flowPositionHandler";
const formLabelWidth = "80px";
const currentNodeId = ref<string | null>(null); // 当前操作的节点 ID
const nodes = ref<Node[]>([]);
const edges = ref<Edge[]>([]);
const route = useRoute();
const router = useRouter();
const projectId = route.params.projectId as string;
const typeId = route.params.typeId as string;
const id = route.params.id as string;
const materialOrProductName = ref<string>("");
const inputRuleFormRef = ref<FormInstance>();
const outputRuleFormRef = ref<FormInstance>();
const inputForm = reactive({
  consumption: "",
  unit: ""
});
const outputForm = reactive({
  consumption: "",
  unit: ""
});
const detailForm = reactive({
  processId: "", // 工序编号
  processName: "", // 工序名称
  description: "" // 工艺描述
});

// 设备绑定只读数据
const equipmentBindings = ref<any[]>([]);

// 设备名称映射
const equipmentNameMap = ref<Record<number, string>>({});
// 拉取一次设备表
const loadEquipmentMap = async () => {
  if (Object.keys(equipmentNameMap.value).length) return;
  const userInfo = JSON.parse(localStorage.getItem("userInfo") || "{}");
  const userId = Number(userInfo.id) || 0;
  try {
    const res = await axios.post(`${baseUrl}/api/carbon/getAllEquipments`, { userId });
    if (res.data?.code === 200) {
      (res.data.data || []).forEach((item: any) => {
        equipmentNameMap.value[item.id] = item.equipmentName;
      });
    }
  } catch (e) {
    console.warn("获取设备列表失败", e);
  }
};

const isComponentMounted = ref(false);
const isDataProcessing = ref(false); // 添加数据处理状态标志

//后端流程图数据列表
const flowChartList = ref<any[]>([]);
//后端基础地址
const baseUrl = import.meta.env.VITE_BASE_URL;

const inputRules = reactive({
  consumption: [{ required: true, message: "请输入能源消耗量", trigger: "blur" }],
  unit: [{ required: true, message: "请选择单位", trigger: "blur" }]
});
const outputRules = reactive({
  consumption: [{ required: true, message: "请输入数量", trigger: "blur" }], // 数量
  unit: [{ required: true, message: "请选择单位", trigger: "blur" }] // 单位
});

// ====================== 获取流程图数据 ======================
const fetchFlowChartList = async () => {
  try {
    const res = await axios.get(`${baseUrl}/api/carbon/getFlowchart`, {
      params: { projectId, objectId: id }
    });
    console.log("processflow获取流程图数据:", res.data);
    if (res.data && res.data.code === 200) {
      flowChartList.value = res.data.data?.nodes || [];
    } else {
      ElMessage.error(res.data.msg || "获取流程图失败");
    }
  } catch (error) {
    console.error("获取流程图出错:", error);
    ElMessage.error("获取流程图失败");
  }
};

// 获取物料详情
const fetchMaterialDetail = async (userId: number, materialId: number) => {
  try {
    const detailRes = await axios.post(`${baseUrl}/api/carbon/getMaterialById?materialId=${materialId}`, {
      userId: userId
    });
    if (detailRes.data?.code === 200) {
      materialOrProductName.value = detailRes.data.data?.materialName || "";
    }
  } catch (error) {
    console.error("获取物料详情失败", error);
  }
};

// 获取物料工序数据
const fetchMaterialProcesses = async (materialId: number) => {
  try {
    const res = await axios.get(`${baseUrl}/api/carbon/getMaterialProcessesEquipment`, {
      params: { projectId, materialId }
    });
    console.log("获取物料流程(含设备):", res.data);
    if (res.data?.code === 200) {
      return res.data.data || [];
    }
    ElMessage.warning(res.data?.msg || "获取物料流程数据失败");
    return [];
  } catch (error) {
    console.error("获取物料流程数据失败:", error);
    ElMessage.error("获取物料流程数据失败");
    return [];
  }
};

// 获取装配流程数据（装配流程固定 object_type=0，按 projectId 取设备）
const fetchAssemblyProcesses = async (projId: number) => {
  try {
    const res = await axios.get(`${baseUrl}/api/carbon/getProjectProcessesEquipment`, {
      params: { projectId: projId }
    });
    console.log("获取装配流程数据:", res.data);
    if (res.data?.code === 200) {
      return res.data.data || [];
    }
    ElMessage.warning(res.data?.msg || "获取装配流程数据失败");
    return [];
  } catch (error) {
    console.error("获取装配流程数据失败:", error);
    ElMessage.error("获取装配流程数据失败");
    return [];
  }
};

// 从后端获取项目信息
const fetchProjectDetails = async (projectId: string) => {
  try {
    const userInfo = JSON.parse(localStorage.getItem("userInfo") || "{}");
    const userId = Number(userInfo.id) || 0;

    const res = await axios.post(`${baseUrl}/api/carbon/getProjectById?projectId=${projectId}`, {
      userId: userId
    });
    console.log("从后端获取项目信息:", res.data);
    if (res.data?.code === 200) {
      return res.data.data;
    }
    ElMessage.warning(res.data?.msg || "获取项目信息失败");
    return null;
  } catch (error) {
    console.error("获取项目信息失败:", error);
    ElMessage.error("获取项目信息失败");
    return null;
  }
};

// 初始化装配流程
const initializeAssemblyProcess = async () => {
  // 获取项目信息
  const projectInfo = await fetchProjectDetails(projectId);
  if (!projectInfo) {
    return;
  }

  const productId = projectInfo.productId;
  if (!productId) {
    ElMessage.warning("项目未关联产品");
    return;
  }

  const processData = await fetchAssemblyProcesses(Number(productId));
  if (processData.length === 0) {
    nodes.value = [];
    edges.value = [];
    return;
  }

  const { nodes: newNodes, edges: newEdges } = initializeFlowChart(processData, {
    spacing: 170,
    isEmission: 0
  });

  nodes.value = newNodes;
  edges.value = newEdges;
};

// 初始化物料流程
const initializeMaterialProcess = async () => {
  const userInfo = JSON.parse(localStorage.getItem("userInfo") || "{}");
  const userId = Number(userInfo.id) || 0;
  const materialId = Number(id);

  // 获取物料详情
  await fetchMaterialDetail(userId, materialId);
  // 获取物料工序数据
  const processes = await fetchMaterialProcesses(materialId);

  if (processes.length === 0) {
    nodes.value = [];
    edges.value = [];
    return;
  }

  const { nodes: newNodes, edges: newEdges } = initializeFlowChart(processes, {
    spacing: 170,
    isEmission: 0
  });

  nodes.value = newNodes;
  edges.value = newEdges;
};

const initializeNodesAndEdges = async () => {
  isDataProcessing.value = true;

  try {
    if (typeId === "0") {
      await initializeAssemblyProcess();
    } else if (typeId === "1") {
      await initializeMaterialProcess();
    }

    // 初始化输入输出节点
    const { nodes: updatedNodes, edges: updatedEdges } = initializeIONodes(
      projectId,
      typeId,
      id,
      nodes.value,
      edges.value,
      flowChartList.value,
      { isProcessFlow: true }
    );

    nodes.value = updatedNodes;
    edges.value = updatedEdges;
  } catch (error) {
    console.error("初始化节点和边时出错:", error);
    ElMessage.error("初始化失败");
  } finally {
    isDataProcessing.value = false;
  }
};

// 动态添加新节点的函数
const isInputModalOpen = ref(false); // 控制模态框显示
const isOutputModalOpen = ref(false); // 控制模态框显示
const isDetailOpen = ref(false);

const openInputModal = () => {
  isInputModalOpen.value = true;
};
const openOutputModal = () => {
  isOutputModalOpen.value = true;
};
// const openDetailModal = () => {
//   isDetailOpen.value = true;
// };

const openDataSourceDialog = () => {
  dataSourceDialogVisible.value = true;
};

// 打开选择分配层次对话框
const openAllocationLevelModal = () => {
  allocationLevelDialogVisible.value = true; // 打开选择分配层次对话框
};

// 数据来源选项
const dataSources = computed(() => {
  const baseOptions = [
    {
      label: "手工录入",
      value: "manual",
      icon: Edit,
      description: "手工录入数据"
    },
    {
      label: "环境数据库",
      value: "database",
      icon: Document,
      description: "从环境数据库中获取"
    },
    {
      label: "物联网系统",
      value: "iot",
      icon: Connection,
      description: "从物联网设备实时获取数据"
    },
    {
      label: "企业信息系统",
      value: "enterpriseSystem",
      icon: Platform,
      description: "从企业信息系统中获取"
    },
    {
      label: "分配获取",
      value: "allocation",
      icon: Share,
      description: "从分配数据中获取"
    }
  ];
  return baseOptions;
});

const dataSourceDialogVisible = ref(false);
const allocationLevelDialogVisible = ref(false);
const selectedAllocationLevel = ref("");

// 分配层次选项
const allocationLevels = computed(() => [
  {
    label: "产品层",
    value: "产品层",
    icon: Document,
    description: "按产品进行分配"
  },
  {
    label: "产线层",
    value: "产线层",
    icon: Connection,
    description: "按产线进行分配"
  },
  {
    label: "设备层",
    value: "设备层",
    icon: Platform,
    description: "按设备进行分配"
  }
]);

// 处理分配层次选择
const handleAllocationLevelSelect = (level: string) => {
  selectedAllocationLevel.value = level;
  confirmAllocationLevel();
};

// 处理数据来源选择
const handleDataSourceSelect = (sourceType: string) => {
  dataSourceDialogVisible.value = false;
  switch (sourceType) {
    case "manual":
      openInputModal();
      break;
    case "database":
      ElMessage.info("数据库获取功能开发中");
      break;
    case "iot":
      ElMessage.info("物联网设备获取功能开发中");
      break;
    case "allocation":
      openAllocationLevelModal();
      break;
    case "enterpriseSystem":
      ElMessage.info("企业信息系统获取功能开发中");
      break;
  }
};

// 确认选择的分配层次
const confirmAllocationLevel = () => {
  // 更新节点数据
  nodes.value = nodes.value.map(node => {
    if (node.id === currentNodeId.value) {
      return {
        ...node,
        data: {
          ...node.data,
          dataSource: "分配获取", // 添加数据来源字段
          consumption: "", // 清空消耗量
          unit: "" // 清空单位
        }
      };
    }
    return node;
  });

  console.log("更新后的节点数据:", nodes.value);
  allocationLevelDialogVisible.value = false; // 关闭对话框
  ElMessage.success("分配层次选择成功！");
};

// 添加新的响应式变量
const nodeDetailDialogVisible = ref(false);
const currentNodeType = ref<"input" | "output">("input");
const currentNodeDetail = ref<any>({});

// 添加工具函数
const getFactorTypeLabel = (value: string | number) => {
  return factorType.find(item => item.value === value)?.label || "暂未定义";
};

const getOutputTypeLabel = (value: string | number) => {
  return outputType.find(item => item.value === value)?.label || "暂未定义";
};

const getUnitLabel = (value: string | number) => {
  return IOUnitType.find(item => item.value === value)?.label || "暂未定义";
};

const getEquipmentName = (id: number | string) => {
  return equipmentNameMap.value[Number(id)] || `设备${id}`;
};

// 修改 handleToolbarAction 函数
const handleToolbarAction = async (action: string, nodeId: string, type?: string) => {
  currentNodeId.value = nodeId;
  if (action === "添加能耗量") {
    openDataSourceDialog();
  } else if (action === "添加输出量") {
    openOutputModal();
  } else if (action === "查看详情") {
    // 处理查看详情的逻辑
    const currentNode = nodes.value.find(node => node.id === nodeId);
    if (currentNode) {
      // 使用传入的 type 参数来确定节点类型
      if (type === "default") {
        // 如果是默认节点，显示工序详情
        detailForm.processId = currentNode.data.processId || "";
        detailForm.processName = currentNode.data.label || "";
        detailForm.description = currentNode.data.description || "";

        // 设备绑定列表，先确保有名称映射
        await loadEquipmentMap();
        equipmentBindings.value = (currentNode.data.equipments || []).map((e: any) => ({
          equipmentId: e.equipmentId,
          equipmentName: equipmentNameMap.value[e.equipmentId] || `设备${e.equipmentId}`
        }));
        isDetailOpen.value = true;
      } else {
        await loadEquipmentMap();
        currentNodeType.value = type as "input" | "output";
        currentNodeDetail.value = currentNode.data;
        nodeDetailDialogVisible.value = true;
      }
    }
  }
};

const save = () => {
  try {
    saveFlowChart(nodes.value, edges.value, Number(projectId), typeId, id, flowChartList.value, { isProcessFlow: true });
    ElMessage({
      type: "success",
      message: "保存成功！"
    });
  } catch (error) {
    console.error("保存失败:", error);
    ElMessage({
      type: "error",
      message: "保存失败，请重试！"
    });
  }
};

// 返回按钮处理函数
const handleBack = async () => {
  console.log("开始处理返回操作");

  // 如果正在处理数据，等待处理完成
  if (isDataProcessing.value) {
    console.log("等待数据处理完成...");
    await new Promise(resolve => {
      const unwatch = watch(isDataProcessing, newVal => {
        if (!newVal) {
          unwatch();
          resolve(true);
        }
      });
    });
  }

  // 确保状态清理完成
  isComponentMounted.value = false;
  nodes.value = [];
  edges.value = [];
  await nextTick();

  router.push(`/lca/inventory/materialIndex/${projectId}`);
};

onMounted(async () => {
  isComponentMounted.value = true;
  console.log("组件挂载，开始初始化...");
  await fetchFlowChartList();
  await initializeNodesAndEdges();
});

onBeforeUnmount(async () => {
  // 等待数据处理完成
  if (isDataProcessing.value) {
    await new Promise(resolve => {
      const unwatch = watch(isDataProcessing, newVal => {
        if (!newVal) {
          unwatch();
          resolve(true);
        }
      });
    });
  }

  isComponentMounted.value = false;
  nodes.value = [];
  edges.value = [];
});

// 添加路由进入的钩子
const init = async () => {
  console.log("重新初始化组件...");
  isComponentMounted.value = true;
  await fetchFlowChartList();
  await initializeNodesAndEdges();
};

// 监听路由变化
watch(
  () => route.fullPath,
  () => {
    if (route.name === "processFlow") {
      init();
    }
  }
);

// 添加数字验证方法
const validateNumber = (field: string, formData: any) => {
  if (isNaN(Number(formData[field]))) {
    formData[field] = formData[field].replace(/[^0-9.]/g, "");
  }
  // 移除开头的零
  formData[field] = formData[field].replace(/^0+(?=\d)/, "");
};

// 添加更新节点能耗数据的方法
const updateNodeConsumption = () => {
  inputRuleFormRef.value!.validate(async valid => {
    if (!valid) return;

    // 使用 map 创建新的数组，以触发响应式更新
    nodes.value = nodes.value.map(node => {
      if (node.id === currentNodeId.value) {
        return {
          ...node,
          data: {
            ...node.data,
            consumption: inputForm.consumption,
            unit: inputForm.unit,
            dataSource: "手工输入" // 添加数据来源字段
          }
        };
      }
      return node;
    });
    // 清空表单
    inputForm.consumption = "";
    inputForm.unit = "";

    // 关闭模态框
    isInputModalOpen.value = false;
    ElMessage.success("能耗数据更新成功！");
  });
};

// 添加更新节点输出数据的方法
const updateNodeOutput = () => {
  outputRuleFormRef.value!.validate(async valid => {
    if (!valid) return;

    // 使用 map 创建新的数组，以触发响应式更新
    nodes.value = nodes.value.map(node => {
      if (node.id === currentNodeId.value) {
        return {
          ...node,
          data: {
            ...node.data,
            consumption: outputForm.consumption,
            unit: outputForm.unit
          }
        };
      }
      return node;
    });
    console.log("更新节点输出数据:", nodes.value);
    // 清空表单
    outputForm.consumption = "";
    outputForm.unit = "";

    // 关闭模态框
    isOutputModalOpen.value = false;
    ElMessage.success("输出数据更新成功！");
  });
};
</script>

<style>
.header {
  display: flex;

  /* 左右分布 */
  align-items: center;
  justify-content: space-between;
  padding: 10px 20px;
  background-color: #ffffff;
  border-bottom: 1px solid #dddddd;
  border-radius: 8px;
}
.header-buttons {
  display: flex;
  gap: 10px;
  margin-left: auto;
}
.back-button {
  padding: 8px 12px;
  margin-right: 20px;
  font-size: 14px;
  color: white;
  cursor: pointer;
  background-color: #009688;
  border: none;
  border-radius: 4px;
  transition: background-color 0.2s ease;
}
.back-button:hover {
  background-color: #007d6a;
}
.title {
  font-size: 18px;
  font-weight: bold;
  color: #333333;
}
.el-button {
  padding: 8px 12px;
  font-size: 14px;
}
.modal-content {
  z-index: 10000;
  width: 300px;
  padding: 20px;
  text-align: center;
  background: white;
  border-radius: 5px;
}
select {
  width: 100%;
  padding: 8px;
  margin: 10px 0;
  border: 1px solid #cccccc;
  border-radius: 4px;
}
.modal {
  position: fixed;
  top: 50%;
  left: 50%;
  z-index: 1000;
  width: 400px;
  max-width: 90%;
  height: auto;
  padding: 20px;
  background-color: white;
  border-radius: 8px;
  transform: translate(-50%, -50%);
}
.vue-flow__node-toolbar {
  display: flex;
  gap: 0.5rem;
  align-items: center;
  padding: 8px;
  background-color: #2d3748;
  border-radius: 8px;
  box-shadow: 0 0 10px rgb(0 0 0 / 50%);
}
.vue-flow__node-toolbar button {
  padding: 0.5rem 1rem;
  color: white;
  cursor: pointer;
  background: #4a5568;
  border: none;
  border-radius: 8px;
}
.vue-flow__node-toolbar button.selected {
  background: #009688;
}
.vue-flow__node-toolbar button:hover {
  background: #009688;
}
.vue-flow__node-default {
  padding: 20px;
  color: #009688;
  background: #e6f5f3;
  border: 1px solid #009688;
  border-radius: 4px;
  box-shadow: 0 0 10px rgb(0 0 0 / 20%);
}
.vue-flow__node-default.selected {
  box-shadow: 0 0 0 0.1px #009688;
}
.vue-flow__node-output {
  width: 200px;
  padding: 8px;
  color: #0078d4;
  background: #dff5fd;
  border: 1px solid #0078d4;
  border-radius: 8px;
  box-shadow: 0 0 10px rgb(0 0 0 / 20%);
}
.vue-flow__node-output.selected {
  box-shadow: 0 0 0 0.1px #0078d4;
}
.vue-flow__node-input {
  width: 200px;
  padding: 8px;
  color: #d4237a;
  background: #fff6fc;
  border: 1px solid #d4237a;
  border-radius: 8px;
  box-shadow: 0 0 10px rgb(0 0 0 / 20%);
}
.vue-flow__node-input.selected {
  box-shadow: 0 0 0 0.1px #d4237a;
}
.data-source-options {
  display: flex;
  flex-direction: column;
  gap: 12px;
  padding: 20px;
}
.data-source-option {
  display: flex;
  align-items: center;
  padding: 16px;
  cursor: pointer;
  background: #ffffff;
  border: 1px solid #e6f5f3;
  border-radius: 8px;
  transition: all 0.3s;
}
.data-source-options > .data-source-option:hover {
  border-color: #009688;
  box-shadow: 0 2px 12px rgb(0 0 0 / 10%);
  transform: translateY(-2px);
}
.source-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 40px;
  height: 40px;
  margin-right: 16px;
  color: #009688;
  background: #e6f5f3;
  border-radius: 8px;
}
.source-info {
  flex: 1;
}
.source-info h4 {
  margin: 0 0 4px;
  font-size: 16px;
  color: #303133;
}
.source-info p {
  margin: 0;
  font-size: 13px;
  color: #909399;
}
.process-flow-container {
  position: relative;
  width: 100%;
  height: calc(100vh - 100px); /* 减去头部高度 */
}
.confirm-flow {
  width: 100%;
  height: 100%;
}

/* 确保节点容器有正确的尺寸 */
.vue-flow__container {
  width: 100%;
  height: 100%;
}

/* 确保节点视图区域正确定位 */
.vue-flow__viewport {
  width: 100%;
  height: 100%;
}
.allocation-level-dialog .dialog-footer {
  display: flex;
  justify-content: flex-end;
  padding: 10px;
}
.allocation-level-options {
  display: flex;
  flex-direction: column;
  gap: 12px;
  padding: 20px;
}
.allocation-level-option {
  display: flex;
  align-items: center;
  padding: 16px;
  cursor: pointer;
  background: #ffffff;
  border: 1px solid #e6f5f3;
  border-radius: 8px;
  transition: all 0.3s;
}
.allocation-level-option:hover {
  border-color: #009688;
  box-shadow: 0 2px 12px rgb(0 0 0 / 10%);
  transform: translateY(-2px);
}
.level-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 40px;
  height: 40px;
  margin-right: 16px;
  color: #009688;
  background: #e6f5f3;
  border-radius: 8px;
}
.level-info {
  flex: 1;
}
.level-info h4 {
  margin: 0 0 4px;
  font-size: 16px;
  color: #303133;
}
.level-info p {
  margin: 0;
  font-size: 13px;
  color: #909399;
}
.el-descriptions {
  padding: 20px;
}
.el-descriptions-item__label {
  width: 120px;
  color: #606266;
}
.el-descriptions-item__content {
  color: #303133;
}
</style>
